package com.qianniu.napi.admin.web;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.Jinfo;
import com.qianniu.napi.admin.entity.Resource;
import com.qianniu.napi.admin.service.IResourceService;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.ObjectUtil;
import com.qianniu.napi.common.util.WeixinUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.Date;

/**
 * <p>
 * 素材管理
 * </p>
 *
 * @author chenxuebin
 * @since 2018-10-22
 */
@Controller
public class ResourceController {

    private static final Logger logger = LoggerFactory.getLogger(ResourceController.class);

    @Autowired
    private IResourceService resourceService;

    @RequestMapping("admin/resource/index")
    public String index() {
        return "admin/resource";
    }

    @RequestMapping("/admin/resource/list")
    @ResponseBody
    public Page<Resource> list(@RequestParam(value = "offset", required = false) Integer offset,
                               @RequestParam(value = "status", required = false) Integer status,
                               @RequestParam(value = "search", required = false) String search,
                               @RequestParam(value = "limit", required = false) Integer limit) {
        Wrapper<Resource> wrapper = new EntityWrapper<Resource>();
        wrapper.eq("mid", ObjectUtil.getMid());
        if (status != null && status != 99) wrapper.eq("rtype", status);
        if (!Strings.isNullOrEmpty(search)) {
            wrapper.andNew().like("name", search).or().eq("ywid", search);
        }

        wrapper.orderBy("id", false);
        Page<Resource> page = resourceService.selectPage(new Page<Resource>(offset / limit + 1, limit), wrapper);
        return page;
    }

    @RequestMapping("/admin/resource/add")
    public String add(@Valid Resource bean, BindingResult bindingResult) {
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            return null;
        }
        bean.setCreatetime(new Date());
        bean.setMid(ObjectUtil.getMid());
        bean.setUid(ObjectUtil.getUid());
        bean.insert();
        return "admin/resource";
    }

    @RequestMapping("/admin/resource/getResourceById")
    @ResponseBody
    public Resource getResourceById(long id) {
        Resource resource = resourceService.selectById(id);
        return resource;
    }

    @RequestMapping("/admin/resource/deleteOne")
    @ResponseBody
    public int deleteOne(long id) {
        boolean isSucc = resourceService.deleteById(id);
        return isSucc ? 1 : 0;
    }

    @RequestMapping("/admin/resource/modify")
    public String update(Resource bean) {
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        boolean isSuccc = resourceService.updateById(bean);
        if (isSuccc) {
            return "redirect:index";
        }
        return "error";
    }

    @RequestMapping("/admin/resource/setmedia")
    @ResponseBody
    public Jinfo setmedia(Long id) {
        Jinfo info = new Jinfo();
        Resource resource = resourceService.selectById(id);
        String pic = resource.getPic();

        String path = pic.indexOf("//imgcdn.") > 0 ? pic.replace(Constants.IMG_UPLOAD_CDN_HOST, "/fafa/www/images/0cdn/") :
                pic.replace(Constants.IMG_UPLOAD_HOST, "/fafa/www/images/");

        JSONObject jo = WeixinUtil.uploadTempMaterial(Constants.WEIXIN_MATERIAL_IMAGE, path, 72, resource.getMpid());

        if (jo.containsKey("media_id")) {
            Resource nresource = new Resource();
            nresource.setId(id);
            nresource.setMediaid(jo.getString("media_id"));
            nresource.setCreatedat(jo.getLong("created_at"));
            nresource.setIsmedia(1);
            nresource.setModifytime(new Date());
            nresource.updateById();
        } else {
            info.setCode(1);
            info.setMsg(jo.getString("errmsg"));
        }

        return info;
    }

}
